/*
 * Copyright (c) 2017 Qunar.com. All Rights Reserved.
 */
package com.guoyu.project.common.freemarker;

import java.io.IOException;
import java.util.Map;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * @author: libo Date: 17-3-1 Time: 上午11:11
 * @version: \$Id$
 */
public class ExtendsDirective implements TemplateDirectiveModel {

    public final static String DIRECTIVE_NAME = "extends";

    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        String name = FreemarkerSupports.getRequiredArgument(params, "name");
        String encoding = (String) params.get("encoding");
        String includeTemplateName = env.toFullTemplateName(getTemplatePath(env), name);
        env.include(includeTemplateName, encoding, true);
    }

    private String getTemplatePath(Environment env) {
        String templateName = env.getMainTemplate().getName();
        return templateName.lastIndexOf('/') == -1 ? "" : templateName.substring(0, templateName.lastIndexOf('/') + 1);
    }

}
